<?php 

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Tokenwallet;
use app\common\model\Trade as TradeModel;
use app\common\model\trade\Log as Tradelog;
use app\common\model\User;
use app\common\model\Tokenlog;
use app\common\model\Bank;
use fast\Random;
use think\Hook;
use app\common\library\Sms as Smslib;
use app\common\library\Ems as Emslib;
/**
 * 提现和充值
 */
class Inout extends Api
{
	//如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['init'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
        Hook::add('check_paypwd', function ($paypwd) use ($auth) {
            if ($auth->getUser()['payplaintext'] != $paypwd) {
                $this->error('安全密码不正确');
            }
        });

        Hook::add('check_pay', function () use ($auth) {

            $trade_pay = config('site.trade_pay');
            $user = $auth->getUser();
            foreach ($trade_pay as $pay) {
                switch ($pay) {
                    case 'alipay':
                        if (empty($user->alipay)) {
                            $this->error('未完善支付宝信息');
                        }
                        break;
                    case 'wechatwallet':
                        if (empty($user->wechatwallet)) {
                            $this->error('未完善微信信息');
                        }
                        break;
                    case 'bank':
                        $bank = new Bank();
                        $banks=$bank->where('status',1)->where('user_id',$auth->id)->order('default desc,id desc')->select();
                        if (empty($banks)) {
                            $this->error('未完善银行卡信息');
                        }
                        break;
                    case 'eth':
                        if (empty($user->eth)) {
                            $this->error('未完善钱包地址信息');
                        }
                        break;
                    case 'mobile':
                        if (empty($user->mobile)) {
                            $this->error('未完善电话信息');
                        }
                        break;
                    case 'email':
                        if (empty($user->email)) {
                            $this->error('未完善邮箱信息');
                        }
                        break;
                    default:
                        $this->error('收付款信息错误');
                        break;
                }
            }
        });

        Hook::add('get_userpay',function($user_id){
            // $user = $auth->getUser();
            $user = User::get($user_id);
            // var_dump($user);
            $pay['alipay']='';
            $pay['wechatwallet']='';
            $pay['banks']='';
            $pay['eth']='';
            $pay['mobile']='';
            if (!empty($user->alipay)) {
                $pay['alipay'] = $user->alipay;
            }
            if (!empty($user->wechatwallet)) {
                $pay['wechatwallet'] = $user->wechatwallet;
            }
            if (!empty($user->eth)) {
                $pay['eth'] = $user->eth;
            }
            if (!empty($user->mobile)) {
                $pay['mobile'] = $user->mobile;
            }

            $bank = new Bank();
            $banks=$bank->where('status',1)->where('user_id',$user_id)->where('default',1)->find();

            if (!empty($banks)) {
                $pay['banks'] = $banks;
            }
            return $pay;
        });
    }

    /**
     * 初始化
     * @return [type] [description]
     */
    public function init()
    {
        
        $trade_poundage = config('site.trade_poundage');
        // $rate = config('site.trade_exch_rate');
        $yb = db('coin')->where('symbol','USD')->find();
        $fae = db('coin')->where('symbol','FAE')->find();
        $trade_out_poundage = config('site.trade_out_poundage');
        $trade_in_poundage = config('site.trade_in_poundage');
    	$this->success('获取成功',['trade_poundage'=>$trade_poundage,'rate'=>['USD'=>$yb['exch_rate'],'FAE'=>$fae['exch_rate']],'trade_out_poundage'=>$trade_out_poundage,'trade_in_poundage'=>$trade_in_poundage]);
    }

    /**
     *会员体现接口
     * 
     * @ApiParams   (name="num", type="int", required=true, description="要提现的数量")
     * @ApiParams   (name="paypwd", type="string", required=true, description="安全密码")
     * TODO  如果USD改名成 则这里也要更改
     */
    public function moneyout()
    {
    	$num = $this->request->request('num',0);
        $paypwd = $this->request->request('paypwd','');
        Hook::listen("check_paypwd",$paypwd);
        Hook::listen('check_pay');
    	try {
            $token = $this->auth->getUserToken()['USD'];
        } catch (\Exception $e) {
            $token = 0;
        }

        if ($num > $token) {
        	$this->error('余额不足');
        }

        $trade_out_min = config('site.trade_out_min');
        $trade_out_multiple = config('site.trade_out_multiple');
        if ($trade_out_min > $num) {
            $this->error(__('至少要'.$trade_out_min));
        }

        if ($num % $trade_out_multiple != 0) {
            $this->error(__('请输入'.$trade_out_multiple.'的倍数'));
        }

        $coin = db('coin')->where('symbol','USD')->field('id,name,symbol,exch_rate,describe')->find();
        $trademodel = new TradeModel();

        $data = [
        	'action' => 'sell',
        	'user_id'	=>	$this->auth->id,
        	'exch_rate'	=>	$coin['exch_rate'],
        	'num'		=>	$num,
        	'surplusnum'		=>	$num,
        	'symbol'	=>	'USD',
        	'tosymbol'	=>	'USDT',
            'pay'       =>  '$pay'
        ];



        $result = $trademodel->allowField(true)->validate('Trade.add')->save($data);
        // echo $trademodel->getLastSql();die;
        if(false === $result){
            $this->error($trademodel->getError());
        }else{
            User::tokenlog('USD',$this->auth->id,0,-$num,'sell','卖出-提现');
            $trade_out_poundage = config('site.trade_out_poundage');
            User::tokenlog('USD',$this->auth->id,0,-$num*bcdiv($trade_out_poundage, 100,3),'sell_poundage','卖出扣除手续费');
            // TODO user 静态方法 扣除钱包 并写入记录
        }
        $this->success('委托提现成功');

    }

    /**
     *会员充值接口
     * 
     * @ApiParams   (name="num", type="int", required=true, description="要充值的数量")
     * @ApiParams   (name="paypwd", type="string", required=true, description="安全密码")
     * TODO  如果USD改名成 则这里也要更改
     */
    public function moneyin()
    {
    	$num = $this->request->request('num');
        $paypwd = $this->request->request('paypwd','');
        Hook::listen("check_paypwd",$paypwd);

        Hook::listen('check_pay');

    	try {
            $token = $this->auth->getUserToken()['USD'];
        } catch (\Exception $e) {
            $token = 0;
        }
        // if ($num > $token) {
        // 	$this->error('余额不足');
        // }
        // $coin = db('coin')->where('symbol','Y')->field('id,name,symbol,exch_rate,describe')->find();
        // 
        $trade_out_min = config('site.trade_out_min');
        $trade_out_multiple = config('site.trade_out_multiple');
        if ($trade_out_min > $num) {
            $this->error(__('不能少于'.$trade_out_min));
        }

        if ($num % $trade_out_multiple != 0) {
            $this->error(__('请输入'.$trade_out_multiple.'的倍数'));
        }

        $trademodel = new TradeModel();
        // $record = $trademodel->where('user_id',$this->auth->id)->where('symbol','USD')->where('tosymbol','USDT')->where('status','in',[0,1])->find();
        // if ($record) {
        // 	$this->error('每人只能有一条委托购买的记录');
        // }
        $data = [
        	'action' => 'buy',
        	'user_id'	=>	$this->auth->id,
        	'exch_rate'	=>	1,
        	'num'		=>	$num,
        	'surplusnum'	=>	$num,
        	'symbol'	=>	'USD',
        	'tosymbol'	=>	'USDT',
            'pay'       =>  '$pay'
        ];
        $result = $trademodel->allowField(true)->validate('Trade.add')->save($data);
        if(false === $result){
            $this->error($trademodel->getError());
        }else{
            // User::tokenlog('USD',$this->auth->id,0,-$num,'buy','买入-充值');
            // TODO user 静态方法 扣除钱包 并写入记录
        }
        $this->success('委托购买成功');
    }


    /**
     * 我的交易订单 提现和充值 
     * @ApiParams   (name="action", type="string", required=true, description="买入卖出查询  buy  sell")
     * @ApiParams   (name="type", type="int", required=true, description="0=>等待中（未开始交易）,1=>进行中,2=>已完成，3=>撤销,4=>锁定中,5=>异常")
     * @ApiParams   (name="page", type="int", required=true, description="当前页数")
     * @return [type] [description]
     */
    public function orderlist()
    {
        $status = $this->request->request('status',0);
        $action = $this->request->request('action','');
        if (!in_array($action, ['buy','sell','all'])) {
            $this->error('传值错误');
        }
        $where=[];
        // if ($action != 'all') {
        //     $where['action']=$action;
        //     if ($action == 'sell') {
        //     	$where['symbol']='USD';
        //     	$where['tosymbol']='USDT';
        //     }else{
        //     	$where['symbol']='USDT';
        //     	$where['tosymbol']='USD';
        //     }
        // }
        if ($status != -1) {
            $where['status']=$status;
        }
        $trademodel = new TradeModel();
        $orders = $trademodel->where('user_id',$this->auth->id)->where('symbol','USD')->where('tosymbol','USDT')->where($where)->limit(10)->page(input('page/d',1))->select();
        $this->success('返回成功',['list'=>$orders]);
    }


    /**
     * 获取交易场上 挂卖或挂买订单
     * @param string $action 查询挂卖或挂买  buy or sell
     * @return [type] [description]
     */
    public function getTradeList()
    {
        // $this->success('返回成功',['list'=>[]]);
        $page = $this->request->request('page/d',1);
        $action = $this->request->request('action','');
        if (!in_array($action, ['buy','sell'])) {
            $this->error('查询异常，buy or sell');
        }
        $trademodel = new TradeModel();
        $trades = $trademodel
            ->where('symbol','USD')
            ->where('tosymbol','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('action',$action)
            ->page($page)
            ->limit(15)
            ->select();
        foreach ($trades as $key => $value) {
            $value->user;
        }
        $this->success('返回成功',['list'=>$trades]);
    }

    /**
     * 获取详细的交易信息
     * @param string $action 查询挂卖或挂买  buy or sell
     * @return [type] [description]
     */
    public function getTradeDetailByid()
    {
        $id = $this->request->request('id/d',0);

        $trademodel = new TradeModel();
        $trade = $trademodel
            ->where('symbol','USD')
            ->where('tosymbol','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('id',$id)
            ->find();
        $trade->user;
        $this->success('返回成功',['info'=>$trade]);
    }

    /**
     * 自己寻找挂卖订单 使用 货币将另一种货币买下
     * symbol是买家卖出的 的货币  tosymbol 是卖家想要
     * @return [type] [description]
     */
    public function selfbuy()
    {
        $id = $this->request->request('id/d');
        $num = $this->request->request('num/d');
        if (!$id) {
            $this->error('请传入ID');
        }
        if (!$num) {
            $this->error('请传入买入数量');
        }

        $paypwd = $this->request->request('paypwd','');
        Hook::listen("check_paypwd",$paypwd);
        // Hook::listen('check_pay');

        $trade_in_min = config('site.trade_in_min');
        $trade_in_multiple = config('site.trade_in_multiple');
        if ($trade_in_min > $num) {
            $this->error(__('不能少于'.$trade_in_min));
        }

        if ($num % $trade_in_multiple != 0) {
            $this->error(__('请输入'.$trade_in_multiple.'的倍数'));
        }

        $trademodel = new TradeModel();
        $trade = $trademodel->where('user_id','<>',$this->auth->id)->where('surplusnum','>',0)->where('id',$id)->where('action','sell')->find();
        if (!$trade) {
            $this->error('没有找到该订单');
        }
        if (!in_array($trade['status'], [0,1])) {
            $this->error('订单已经被人抢先一步了！');
        }

        if ($num > $trade['surplusnum']) {
            $this->error('数量不足，请刷新重试');
        }

        // try {
        //     $token = $this->auth->getUserToken()[$trade['tosymbol']];
        // } catch (\Exception $e) {
        //     $token = 0;
        // }

        // $tradenum = bcmul($num, $trade['exch_rate'],2);
        // if ($token < $tradenum) {
        //     $this->error('您的货币不足 '.$trade['symbol']);
        // }

        $trademodel->where('id',$trade->id)->dec('surplusnum',$num)->update(['status'=>1]);
        
        $userinfo =$this->auth->getUserinfo();
        $action = request()->action();
        $username = $userinfo['username'];
        $tradeno = Random::tradeno();
        Tradelog::Log($tradeno,$this->auth->id,$username,0,$trade->user_id,$trade->user->username,$trade->id,$num,$num,$num,'waitting',$action,$trade['symbol'],$trade['tosymbol']);

        $msg = "您订单号为{$tradeno}，买入USD{$num}个，订单已经匹配成功，请及时登录后台，查找卖方信息并及时转账。如您30分钟内没有转账系统将取消这笔订单。恶意操作，可能造成封号。";
        if ($userinfo['mobile']) {
            Smslib::notice($userinfo['mobile'],$msg);
        }

        $this->success('交易成功');
    }


    /**
     * 自己寻找挂买订单 使用 货币将另一种货币买下
     * symbol是买家卖出的 的货币  tosymbol 是卖家想要
     * @return [type] [description]
     */
    public function selfsell()
    {
        $id = $this->request->request('id/d');
        $num = $this->request->request('num/d');
        if (!$id) {
            $this->error('请传入ID');
        }
        if (!$num) {
            $this->error('请传入卖出数量');
        }
        $paypwd = $this->request->request('paypwd','');
        Hook::listen("check_paypwd",$paypwd);
        

        Hook::listen('check_pay');

        $trade_in_min = config('site.trade_in_min');
        $trade_in_multiple = config('site.trade_in_multiple');
        if ($trade_in_min > $num) {
            $this->error(__('不能少于'.$trade_in_min));
        }

        if ($num % $trade_in_multiple != 0) {
            $this->error(__('请输入'.$trade_in_multiple.'的倍数'));
        }


        $trademodel = new TradeModel();
        $trade = $trademodel->where('user_id','<>',$this->auth->id)->where('surplusnum','>',0)->where('id',$id)->where('action','buy')->find();
        if (!$trade) {
            $this->error('没有找到该订单');
        }
        if (!in_array($trade['status'], [0,1])) {
            $this->error('订单已经被人抢先一步了！');
        }

        if ($num > $trade['surplusnum']) {
            $this->error('数量不足，请刷新重试');
        }

        try {
            $token = $this->auth->getUserToken()['USD'];
        } catch (\Exception $e) {
            $token = 0;
        }

        $tradenum = bcmul($num, $trade['exch_rate'],2);
        if ($token < $tradenum) {
            $this->error('您的货币不足 '.$trade['symbol']);
        }

        User::tokenlog($trade['symbol'],$this->auth->id,0,-$tradenum,'selfsell','主动寻找买家卖出');
        $trade_out_poundage = config('site.trade_out_poundage');
        User::tokenlog('USD',$this->auth->id,0,-$tradenum*bcdiv($trade_out_poundage, 100,3),'sell_poundage','卖出扣除手续费');
        
        $trademodel->where('id',$trade->id)->dec('surplusnum',$num)->update(['status'=>1]);

        $action = request()->action();
        $username = $this->auth->getUserinfo()['username'];
        // Tradelog::Log(Random::tradeno(),$this->auth->id,$username,0,$trade->user_id,$trade->user->username,$trade->id,$num,$num,$num,'waitting',$action,$trade['symbol'],$trade['tosymbol']);
        $tradeno = Random::tradeno();
        Tradelog::Log($tradeno,$trade->user_id,$trade->user->username,$trade->id,$this->auth->id,$username,0,$num,$num,$num,'waitting',$action,$trade['symbol'],$trade['tosymbol']);
        $user_buy = User::get($trade->user_id);
        // var_dump($user_buy);

        if ($user_buy->mobile) {
            $msg = "您订单号为{$tradeno}，买入USD{$num}个，订单已经匹配成功，请及时登录后台，查找卖方信息并及时转账。如您30分钟内没有转账系统将取消这笔订单。恶意操作，可能造成封号。";

            Smslib::notice($user_buy->mobile,$msg);
        }


        $this->success('卖出成功');
    }



    /**
     * 我的交易订单 提现和充值
     * @ApiParams   (name="action", type="string", required=true, description="买入卖出查询  buy  sell")
     * @ApiParams   (name="type", type="int", required=true, description="0=>等待中（未开始交易）,1=>进行中,2=>已完成，3=>撤销,4=>锁定中,5=>异常")
     * @ApiParams   (name="page", type="int", required=true, description="当前页数")
     * @return [type] [description]
     */
    public function getmyorders()
    {
        // $this->success('返回成功',['list'=>[]]);
        $status = $this->request->request('status','');
        $where=[];
        if ($status != -1) {
            $where['status']=$status;
        }
        $tradelog = new Tradelog();
        $orders = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)
            ->where('symbol','USD')->where('tosymbol','USDT')
            ->where($where)
            ->limit(10)
            ->order('id desc')
            ->page(input('page/d',1))
            ->select();
        $this->success('返回成功',['list'=>$orders]);
    }


    /**
     * 获取我的发布
     * @param string $action 查询挂卖或挂买  buy or sell
     * @return [type] [description]
     */
    public function getmypublish()
    {
        $page = $this->request->request('page/d',1);
        $trademodel = new TradeModel();
        $trades = $trademodel
            ->where('symbol|tosymbol','USDT')
            ->where('user_id',$this->auth->id)
            ->page($page)
            ->order('id desc')
            ->limit(15)
            ->select();

        $this->success('返回成功',['list'=>$trades]);
    }


    /**
     * 交易订单明细
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function tradeorderinfo()
    {
        $id = $this->request->request('id/d',0);
        if (!$id) {
            $this->error('订单id传入错误');
        }
        $trademodel = new TradeModel();
        $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        if (!$order) {
            $this->error('订单被外星人劫持');
        }

        $user_id = $this->auth->id;
        $userpay = Hook::listen("get_userpay",$user_id);
        $order->pay = $userpay[0];


        $tradelog = new Tradelog();

        $step1 =  config('site.trade_dispute_time_step1');
        $step2 =  config('site.trade_dispute_time_step2');
        switch ($order->action) {
            case 'sell':
                $tradelogs = $tradelog->where('sell_trade_id',$order->id)->select();
                foreach ($tradelogs as &$log) {
                    if ($log->status == 'waitting' && ($log->createtime + $step1*60 < time())) {
                        $log->allowdispute = 1;
                    }elseif($log->status == 'affirm'){
                        $log->allowdispute = 1;
                    }else{
                        $log->allowdispute = 0;
                    }

                    $user_id = $log->buy_user_id;
                    $touserpay = Hook::listen("get_userpay",$user_id);
                    $log->pay = $touserpay[0];

                }
                $order->tradelogs   =$tradelogs;
                break;
            case 'buy':
                $tradelogs = $tradelog->where('buy_trade_id',$order->id)->select();
                foreach ($tradelogs as &$log) {
                    if ($log->status == 'waitting' && ($log->createtime + $step1*60 < time())) {
                        $log->allowdispute = 0;
                    }elseif($log->status == 'affirm' && ($log->updatetime + $step2*60 < time()) ){
                        $log->allowdispute = 1;
                    }else{
                        $log->allowdispute = 0;
                    }
                    $user_id = $log->sell_user_id;
                    $touserpay = Hook::listen("get_userpay",$user_id);
                    $log->pay = $touserpay[0];

                }
                $order->tradelogs = $tradelogs;
                break;
            default:
                $this->error('您的订单数据异常，被外星人篡改了');
                break;
        }

        $this->success('返回成功',['info'=>$order]);
    }

    /**
     * 我的交易详情
     * @ApiParams   (name="id", type="int", required=true, description="匹配订单详情")
     * @return [type] [description]
     */
    public function gettradelog()
    {
        $id = $this->request->request('id/d',0);
        if (!$id) {
            $this->error('订单id传入错误');
        }

        $tradelog = new Tradelog();

        $trade_log = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)->where('id',$id)->find();

        $user_id = $this->auth->id;
        $userpay = Hook::listen("get_userpay",$user_id);
        $trade_log->pay = $userpay[0];


        $step1 =  config('site.trade_dispute_time_step1');
        $step2 =  config('site.trade_dispute_time_step2');

        if ( $trade_log->buy_user_id == $this->auth->id) {
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 0;
            }elseif($trade_log->status == 'affirm' && ($trade_log->updatetime + $step2*60 < time()) ){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }


            $user_id = $trade_log->sell_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];


        }elseif($trade_log->sell_user_id == $this->auth->id){
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 1;
            }elseif($trade_log->status == 'affirm'){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }
            $user_id = $trade_log->buy_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];

        }

        $this->success('返回成功',['info'=>$trade_log]);
    }

    /**
     * 上传凭证
     * @return [type] [description]
     */
    public function voucher()
    {
        $image = $this->request->request('image/s',0);
        $id = $this->request->request('id/d',0);
        $tradelog = new Tradelog();
        $order = $tradelog->where('buy_user_id',$this->auth->id)->where('id',$id)->find();

        $rsp = $tradelog->where('id',$id)->update(['image'=>$image]);
        if ($rsp) {
            $this->success('上传成功');
        }else{
            $this->error('上传失败');
        }
        
    }

/**
     * 确认打款
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function comfirmdakuan()
    {
        $id = $this->request->request('id/d',0);
        $voucher = $this->request->request('voucher/s',0);
        if (!$id) {
            $this->error('订单id传入错误');
        }
        // if (!$voucher) {
        //     $this->error('请上传凭证');
        // }
        // $trademodel = new TradeModel();
        // $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        // if (!$order) {
        //     $this->error('订单被外星人劫持');
        // }

        $tradelog = new Tradelog();

        $order = $tradelog->where('buy_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        // echo $order->status;
        if ($order->status != 'waitting') {
            $this->error('订单状态不正确',['order'=>$order]);
        }
        $tradelog->save(['status'=>'affirm'],['id'=>$id]);
        $sell_user_id = $order['sell_user_id'];

        $userpay = Hook::listen("get_userpay",$sell_user_id);
        $config  = get_addon_config('clsms');
        $event = $config['event'];
        if (isset($event['comfirm'])) {
            $str = $event['comfirm'];
        }
        else {
            return false;
        }
        $str = str_replace('{tradeno}',$order['trade_no'],$str);
        $str = str_replace('{symbol}',$order['symbol'],$str);
        $msg = str_replace('{num}',$order['buy_num'],$str);
        if ($userpay[0]['mobile']) {
            Smslib::notice($userpay[0]['mobile'],$msg);
        }

        $this->success('确认打款',['info'=>$order]);
    }

    /**
     * 确认收款
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function comfirmshoukuan()
    {
        $id = $this->request->request('id/d',0);
        if (!$id) {
            $this->error('订单id传入错误');
        }
        // $trademodel = new TradeModel();
        // $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        // if (!$order) {
        //     $this->error('订单被外星人劫持');
        // }

        $tradelog = new Tradelog();

        $order = $tradelog->where('sell_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        if ($order->status != 'affirm') {
            $this->error('订单状态不正确');
        }

        $tradelog->where('id',$id)->update(['status'=>'finish']);

        $trademodel = new TradeModel();
        $buy_order = $trademodel->where('id',$order->buy_trade_id)->where('surplusnum',0)->find();

        $runningtradebuy = $tradelog->where('buy_trade_id',$order->buy_trade_id)->where('status','in',['waitting','affirm','dispute'])->find();
        if (!$runningtradebuy && $buy_order) {
            $trademodel->where('id',$order->buy_trade_id)->update(['status'=>'2']);
        }
        $runningtradesell = $tradelog->where('sell_trade_id',$order->sell_trade_id)->where('status','in',['waitting','affirm','dispute'])->find();
        $sell_order = $trademodel->where('id',$order->sell_trade_id)->where('surplusnum',0)->find();
        if (!$runningtradesell && $sell_order) {
            $trademodel->where('id',$order->sell_trade_id)->update(['status'=>'2']);
        }

        if ($order->symbol == 'USD' && $order->tosymbol == 'USDT') {
            User::tokenlog($order->symbol,$order->buy_user_id,0,$order->sell_num,'buy','买入到账');
        }
        if ($order->symbol == 'USD' && $order->tosymbol == 'FAE') {
            User::tokenlog($order->symbol,$order->buy_user_id,0,$order->sell_num,'buy','买入到账');
        }
        $this->success('确认收款',['info'=>$order]);
    }


    

    /**
     * 点对点交易  私下交易
     *
     * @ApiParams   (name="username", type="string", required=true, description="收款方用户名")
     * @ApiParams   (name="symbol", type="string", required=true, description="使用那个币汇款")
     * @ApiParams   (name="num", type="int", required=true, description="汇款的数量")
     * @return [type] [description]
     */
    public function pointToPoint()
    {
        $username = $this->request->request('username',0);
        $symbol = $this->request->request('symbol','');
        $num = $this->request->request('num',0);
        // $paypwd = $this->request->request('paypwd','');
        // Hook::listen("check_paypwd",$paypwd);
        

        $exists = \app\common\model\User::where('username', $username)->find();
        if (!$exists)
        {
            $this->error(__('收款方不存在'));
        }
        if ($this->auth->id == $exists->id) {
            $this->error(__('该地址不能转账'));
        }
        $trade_min = config('site.trade_min');
        $trade_multiple = config('site.trade_multiple');
        if ($trade_min > $num) {
            $this->error(__('至少要转'.$trade_min));
        }

        if ($num % $trade_multiple != 0) {
            $this->error(__('请输入'.$trade_multiple.'的倍数'));
        }

        $trade_poundage = config('site.trade_poundage');

        $poundage = $num*$trade_poundage/100;

        try {
            $token = $this->auth->getUserToken()[$symbol];
        } catch (\Exception $e) {
            $token = 0;
        }
        if ($num > $token+$poundage) {
            $this->error(__('余额不足'));
        }

        User::tokenlog($symbol,$this->auth->id,$exists->id,-$num,'transfer-out','转账-转出');
        User::tokenlog($symbol,$this->auth->id,$exists->id,-$poundage,'transfer-poundage','转账-转出手续费');
        User::tokenlog($symbol,$exists->id,$this->auth->id,$num,'transfer-in','转账-转入');

        $this->success(__('转账成功'));
    }

    /**
     * 获取我的转入转出记录
     * @ApiParams   (name="username", type="string", required=true, description="收款方用户名")
     * @ApiParams   (name="type", type="string", required=true, description="查询类型 all=全部  transfer-out=转出  transfer-in=转入")
     * @ApiParams   (name="page", type="int", required=true, description="页数")
     */
    public function getMyTransfer()
    {
        $page = $this->request->request('page',0);
        $type = $this->request->request('type','all');
        $where=[];
        if (!in_array($type, ['all','transfer-out','transfer-in'])) {
            $this->error('查询类型错误');
        }elseif ($type == 'all') {
            $where['type'] =['in',['transfer-out','transfer-in']];
        }elseif ($type != 'all') {
            $where['type'] = $type;
        }


        $tokenlog = new Tokenlog();

        $logs = $tokenlog 
            ->where('user_id',$this->auth->id)
            ->where($where)
            ->order('id desc')
            ->page($page)->limit(10)
            ->select();
        foreach ($logs as &$log) {
            $log['username']=db('user')->where('id',$log['touser_id'])->value('username');
        }

        $this->success('获取成功',['list'=>$logs]);
    }

    public function getTransferLogs()
    {
        $page = $this->request->request('page',0);
        $type = $this->request->request('type','USD');
        $tokenlog = new Tokenlog();

        $logs = $tokenlog 
            ->where('user_id',$this->auth->id)
            ->where('symbol',$type)
            ->order('id desc')
            ->page($page)->limit(15)
            ->select();

        foreach ($logs as $log) {
            
        }
        $this->success('获取成功',['list'=>$logs]);

    }


    /**
     * 申请订单仲裁
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function dispute()
    {
        $id = $this->request->request('id/d',0);
        if (!$id) {
            $this->error('订单id传入错误');
        }

        $tradelog = new Tradelog();

        $order = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        if ($order->status == 'waitting') {
            if($order->sell_user_id == $this->auth->id){
                $disputestatus =$order->status;
            }else{
                $this->error('您不能申请改订单的仲裁');
            }
            
        }elseif($order->status == 'affirm'){
            if ($order->buy_user_id == $this->auth->id) {
                $disputestatus =$order->status.'buy';
            }elseif($order->sell_user_id == $this->auth->id){
                $disputestatus =$order->status.'sell';
            }else{
                $this->error('订单被外星人劫持');
            }
        }else{
            $this->error('订单状态不允许申请仲裁');
        }
        $tradelog->save(['status'=>'dispute','disputestatus'=>$disputestatus],['id'=>$id]);
        $this->success('提交仲裁成功',['info'=>$order]);
    } 
}
 ?>